<template>
  <div>
    <div class="" v-if="falg2">
      <div class="basic">
        <div style="display: flex; align-items: center">
          <div class="Useful">套餐优惠设置</div>
        </div>
        <div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="130px"
            class="demo-ruleForm"
            label-position="left"
          >
            <el-form-item label="套餐商品选择：" prop="goodsPackageDetails">
              <div
                class="checkDete"
                v-for="(item, index) in ruleForm.goodsPackageDetails"
                :key="index"
                style="margin-bottom:5px;"
              >
                <el-select
                  v-model="ruleForm.goodsPackageDetails[index].areaCode"
                  placeholder="请选择"
                  @change="value => changeArea(value, index)"
                >
                  <el-option
                    v-for="item in arealist"
                    :key="item.areaCode"
                    :label="item.areaName"
                    :value="item.areaCode"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="ruleForm.goodsPackageDetails[index].classifyCode"
                  placeholder="请选择"
                  @change="value => changeClass(value, index)"
                >
                  <el-option
                    v-for="item in serveclasslist"
                    :key="item.classifyCode"
                    :label="item.classifyName"
                    :value="item.classifyCode"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="ruleForm.goodsPackageDetails[index].goodsCode"
                  placeholder="请选择"
                  @visible-change="value => getGoodsCodeList(index, value)"
                  :loading="isloading"
                >
                  <el-option
                    v-for="item in ruleForm.goodsPackageDetails[index]
                      .goodsCodeList"
                    :key="item.goodsCode"
                    :label="item.goodsName"
                    :value="item.goodsCode"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="ruleForm.goodsPackageDetails[index].skuId"
                  placeholder="请选择"
                  @visible-change="value => getCraftSelectedVos(index, value)"
                >
                  <el-option
                    v-for="item in ruleForm.goodsPackageDetails[index]
                      .craftSelectedVos"
                    :key="item.skuId"
                    :label="item.skuName"
                    :value="item.skuId"
                  >
                  </el-option>
                </el-select>
                <el-button
                  icon="el-icon-plus"
                  style="background-color:#fd804c;color: #fff;"
                  v-if="index === 0"
                  @click="addGoodsPackageDetails"
                ></el-button>
                <el-button
                  icon="el-icon-minus"
                  style="background-color:#fd804c;color: #fff;"
                  v-if="index !== 0"
                  @click="deleteGoodsPackageDetails(index)"
                ></el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="talbe">
          <div
            class="table1"
            style="width: 30%; margin-right: 10px; font-size:14px;"
          >
            <div style="margin-bottom:10px;">依基础价格设置优惠金额：</div>
            <el-table :data="tableData1" border>
              <el-table-column prop="conturay" label=""> </el-table-column>
              <el-table-column
                prop="goodsPackageTotalPrice"
                label="套餐总额(元)"
              ></el-table-column>
              <el-table-column
                prop="goodsPackageDiscountPrice"
                label="优惠金额"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.goodsPackageDiscountPrice"
                    size="mini"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div
            class="table2"
            style="width: 30%; margin-right: 10px;font-size:14px;"
          >
            <div style="margin-bottom:10px;">
              <span>依城市价格设置优惠金额：</span>
              <el-checkbox v-model="checked2">批量设置</el-checkbox>
            </div>
            <el-table :data="tableData2" border :height="500">
              <el-table-column prop="cityName" label="城市"> </el-table-column>
              <el-table-column
                prop="goodsPackageTotalPrice"
                label="套餐总额(元)"
              >
              </el-table-column>
              <el-table-column
                prop="goodsPackageDiscountPrice"
                label="优惠金额"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.goodsPackageDiscountPrice"
                    size="mini"
                    @input="changeTable2Value"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="table3" style="width:40%;">
            <div style="font-size:14px;margin-bottom:10px;">
              <span>依商圈价格设置优惠金额：</span>
              <el-checkbox v-model="checked3">批量设置</el-checkbox>
            </div>
            <el-table
              :data="tableData3"
              :span-method="objectSpanMethod"
              border
              :height="500"
            >
              <el-table-column prop="cityName" label="城市"> </el-table-column>
              <el-table-column prop="businessAreaName" label="商圈">
              </el-table-column>
              <el-table-column
                prop="goodsPackageTotalPrice"
                label="套餐总额(元)"
              ></el-table-column>
              <el-table-column
                prop="goodsPackageDiscountPrice"
                label="优惠价格"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.goodsPackageDiscountPrice"
                    size="mini"
                    @input="changeTable3Value"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="buttons">
          <el-button
            style="background-color:#fd804c;color: #fff;margin-top: 10px"
            @click="Prew"
            >上一步</el-button
          >
          <el-button
            style="background-color:#fd804c;color: #fff;margin-top: 10px"
            @click="Next('ruleForm')"
            >下一步</el-button
          >
          <el-button
            style="background-color:#fd804c;color: #fff;margin-top: 10px"
            @click="Save('ruleForm')"
            >保存</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Bus from "../../../api/bus";
export default {
  props: {
    goodsPkgDiscountPriceDTO: {
      type: Object,
      required: true
    },
    goodsPackageDetails: {
      type: Array,
      required: true
    }
  },
  data() {
    // 商品套餐选择规则
    var checkgoodsPackageDetails = (rule, value, callback) => {
      value.forEach(item => {
        if (
          item.areaCode == "" ||
          item.classifyCode == "" ||
          item.goodsCode == "" ||
          item.skuId == ""
        ) {
          return callback(new Error("请完整选择套餐商品"));
        }
      });
      callback();
    };
    return {
      isloading: false,
      falg2: false,
      requestUrl: "",
      tableData1: [],
      tableData2: [],
      checked2: false,
      tableData3: [],
      checked3: false,
      ruleForm: {
        goodsPackageDetails: [
          {
            areaCode: "",
            classifyCode: "",
            goodsCode: "",
            skuId: "",
            goodsCodeList: [],
            craftSelectedVos: []
          }
        ]
      },
      arealist: [], //区域
      serveclasslist: [], // 类别
      rules: {
        goodsPackageDetails: [
          { required: true, message: "请选择套餐商品" },
          { validator: checkgoodsPackageDetails }
        ]
      }
    };
  },
  activated() {
    Bus.$on("falg2", data => {
      this.falg2 = data;
    });
    this.getServiceAreaSelectedList();
    this.getServiceClassifySelectedList();
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        // 第一列的合并方法
        const row1 = this.cityNameArr[rowIndex];
        const col1 = row1 > 0 ? 1 : 0;
        return {
          rowspan: row1,
          colspan: col1
        };
      }
    },
    //   下一步
    Next(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          this.$message.error("请将必填项填写完整");
          return false;
        } else {
          // 相同的商品要求客户删除goodsCode相同的商品
          const flag = this.checkHasSameGoodsCode();
          if (flag) {
            this.$message.error(
              "配置商品套餐不可添加相同的商品,相同的商品请仅保留一条"
            );
            return false;
          }
          // 校验套餐的优惠价格不能大于套餐总额
          const flag1 = this.validTable();
          if (!flag1) return;
          setTimeout(() => {
            this.falg2 = false;
            Bus.$emit("falg3", true, "子组件向兄弟组件传值");
          }, 500);
          this.Save("ruleForm");
        }
      });
    },
    Prew() {
      // 上一步
      this.falg2 = false;
      Bus.$emit("falg", true);
    },
    changeTable2Value(value) {
      // 批量修改
      if (this.checked2) {
        this.tableData2.forEach(item => {
          item.goodsPackageDiscountPrice = value;
        });
      }
    },
    changeTable3Value(value) {
      if (this.checked3) {
        this.tableData3.forEach(item => {
          item.goodsPackageDiscountPrice = value;
        });
      }
    },
    merageInit() {
      this.cityNameArr = [];
      this.cityNamePos = 0;
    },
    merage() {
      this.merageInit();
      for (let i = 0; i < this.tableData3.length; i += 1) {
        if (i === 0) {
          // 第一行必须存在
          this.cityNameArr.push(1);
          this.cityNamePos = 0;
        } else {
          if (this.tableData3[i].cityName === this.tableData3[i - 1].cityName) {
            this.cityNameArr[this.cityNamePos] += 1;
            this.cityNameArr.push(0);
          } else {
            this.cityNameArr.push(1);
            this.cityNamePos = i;
          }
        }
      }
    },
    addGoodsPackageDetails() {
      // 增加商品选择item
      // 填写完整新增
      let addFlag = true;
      this.ruleForm.goodsPackageDetails.forEach(item => {
        if (
          item.areaCode == "" ||
          item.classifyCode == "" ||
          item.goodsCode == "" ||
          item.skuId == ""
        ) {
          addFlag = false;
        }
      });
      if (!addFlag) {
        this.$message.error("请先填写完整再新增");
        return false;
      }
      this.ruleForm.goodsPackageDetails.push({
        areaCode: "",
        classifyCode: "",
        goodsCode: "",
        skuId: "",
        goodsCodeList: [],
        craftSelectedVos: []
      });
    },
    deleteGoodsPackageDetails(index) {
      // 删除商品选择item
      // 重新计算套餐价格
      let calculateFlag = false;
      if (this.ruleForm.goodsPackageDetails[index].skuId) {
        calculateFlag = true;
      }
      this.ruleForm.goodsPackageDetails.splice(index, 1);
      if (calculateFlag) {
        this.changeskuIds();
      }
    },
    getServiceAreaSelectedList() {
      // 区域枚举
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceAreaSelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.arealist = data;
      });
    },
    getServiceClassifySelectedList() {
      // 服务分类
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceClassifySelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.serveclasslist = data;
      });
    },
    async getGoodsCodeList(index, value) {
      // 商品枚举查询
      if (
        value &&
        this.ruleForm.goodsPackageDetails[index].areaCode != "" &&
        this.ruleForm.goodsPackageDetails[index].classifyCode != ""
      ) {
        const { data } = await this.$http({
          url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsSelectedList",
          method: "get",
          params: {
            areaCode: this.ruleForm.goodsPackageDetails[index].areaCode,
            classifyCode: this.ruleForm.goodsPackageDetails[index].classifyCode
          }
        });
        this.isloading = false;
        this.ruleForm.goodsPackageDetails[index].goodsCodeList = data;
      }
    },
    getCraftSelectedVos(index, value) {
      // 获取商品规格枚举
      const currentareaCode = this.ruleForm.goodsPackageDetails[index].areaCode;
      const currentclassifyCode = this.ruleForm.goodsPackageDetails[index]
        .classifyCode;
      const currentgoodsCode = this.ruleForm.goodsPackageDetails[index]
        .goodsCode;
      if (
        value &&
        currentareaCode != "" &&
        currentclassifyCode != "" &&
        currentgoodsCode != ""
      ) {
        const currentObj = this.ruleForm.goodsPackageDetails[
          index
        ].goodsCodeList.find(item => item.goodsCode === currentgoodsCode);
        this.ruleForm.goodsPackageDetails[index].craftSelectedVos =
          currentObj.craftSelectedVos;
      }
      if (!value && this.ruleForm.goodsPackageDetails[index].skuId) {
        // 重新计算套餐价格
        this.changeskuIds();
      }
    },
    changeArea(value, index) {
      // 区域值改变
      if (this.ruleForm.goodsPackageDetails[index].skuId) {
        this.ruleForm.goodsPackageDetails[index].goodsCode = "";
        this.ruleForm.goodsPackageDetails[index].skuId = "";
        this.changeskuIds();
      }
    },
    changeClass(value, index) {
      if (this.ruleForm.goodsPackageDetails[index].skuId) {
        this.ruleForm.goodsPackageDetails[index].goodsCode = "";
        this.ruleForm.goodsPackageDetails[index].skuId = "";
        this.changeskuIds();
      }
    },
    async changeskuIds() {
      // 优惠套餐价格查询
      let baseUrl =
        "/hssgoodsadmin/serviceGoodsPkg/calculateGoodsPkgDiscountPrice?";
      const skuIdArr = [];
      this.ruleForm.goodsPackageDetails.forEach((item, index) => {
        if (item.skuId) {
          skuIdArr.push(item.skuId);
        }
      });
      if (skuIdArr.length > 0) {
        skuIdArr.forEach((item, index) => {
          if (index == 0) {
            baseUrl += `skuIds=${item}`;
          } else {
            baseUrl += `&skuIds=${item}`;
          }
        });
      }
      if (skuIdArr.length == 0) {
        this.tableData1 = [];
        this.tableData2 = [];
        this.tableData3 = [];
        return false;
      }
      const { data } = await this.$http({
        url: baseUrl,
        method: "get"
      });
      const {
        baseDiscountPrice,
        cityDiscountPrices,
        businessAreaDiscountPrices
      } = data;
      this.tableData1 = [
        {
          conturay: "全国统一",
          goodsPackageTotalPrice: baseDiscountPrice.goodsPackageTotalPrice,
          goodsPackageDiscountPrice: baseDiscountPrice.goodsPackageDiscountPrice
        }
      ];
      this.tableData2 = cityDiscountPrices;
      this.tableData3 = businessAreaDiscountPrices;
      this.merage();
    },
    async Save(formName) {
      // 套餐价格保存
      // 规则校验
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          this.$message.error("请将必填项填写完整");
          return false;
        } else {
          // 相同的商品要求客户删除goodsCode相同的商品
          const flag = this.checkHasSameGoodsCode();
          if (flag) {
            this.$message.error(
              "配置商品套餐不可添加相同的商品,相同的商品请仅保留一条"
            );
            return false;
          }
          // 校验套餐的优惠价格不能大于套餐总额
          const flag1 = this.validTable();
          if (!flag1) return;
          const goodsPackageDetails = this.ruleForm.goodsPackageDetails.map(
            item => {
              const obj = {
                areaCode: item.areaCode,
                subClassifyCode: item.classifyCode,
                goodsCode: item.goodsCode,
                skuId: item.skuId
              };
              return obj;
            }
          );
          const cityDiscountPrices = this.tableData2.map(item => {
            return {
              cityCode: item.cityCode,
              cityName: item.cityName,
              goodsPackageTotalPrice: item.goodsPackageTotalPrice,
              goodsPackageDiscountPrice: item.goodsPackageDiscountPrice
                ? Number(item.goodsPackageDiscountPrice)
                : 0
            };
          });
          const businessAreaDiscountPrices = this.tableData3.map(item => {
            return {
              businessAreaCode: item.businessAreaCode,
              businessAreaName: item.businessAreaName,
              cityCode: item.cityCode,
              cityName: item.cityName,
              goodsPackageTotalPrice: item.goodsPackageTotalPrice,
              goodsPackageDiscountPrice: item.goodsPackageDiscountPrice
                ? Number(item.goodsPackageDiscountPrice)
                : 0
            };
          });
          const goodsPkgDiscountPriceDTO = {
            baseDiscountPrice: {
              goodsPackageTotalPrice: this.tableData1[0].goodsPackageTotalPrice,
              goodsPackageDiscountPrice: this.tableData1[0]
                .goodsPackageDiscountPrice
                ? Number(this.tableData1[0].goodsPackageDiscountPrice)
                : 0
            },
            cityDiscountPrices,
            businessAreaDiscountPrices
          };
          const data = {
            goodsPackageCode: this.$route.query.goodsPackageCode,
            goodsPackageDetails,
            goodsPkgDiscountPriceDTO
          };
          const res = await this.$http({
            url:
              "/hssgoodsadmin/serviceGoodsPkg/updateGoodsPackageDiscountPrice",
            method: "POST",
            data
          });
          if (res.success === 1) {
            // this.$message.success('当前页面数据保存成功')
            this.$emit("research");
          }
        }
      });
    },
    checkHasSameGoodsCode() {
      const goodsCodeList = [];
      this.ruleForm.goodsPackageDetails.forEach(item => {
        if (goodsCodeList.indexOf(item.goodsCode) === -1) {
          goodsCodeList.push(item.goodsCode);
        }
      });
      if (goodsCodeList.length < this.ruleForm.goodsPackageDetails.length) {
        return true;
      } else {
        return false;
      }
    },
    validTable() {
      // 表格数字大小的校验
      let flag = true;
      if (
        this.tableData1[0].goodsPackageDiscountPrice >
        this.tableData1[0].goodsPackageTotalPrice
      ) {
        flag = false;
        this.$message.error("基础价格配置的优惠价格大于套餐总额");
      }
      if (!flag) return;
      this.tableData2.forEach((item, index) => {
        if (item.goodsPackageDiscountPrice > item.goodsPackageTotalPrice) {
          flag = false;
          this.$message.error(`${item.cityName}配置的优惠价格大于套餐总额`);
          throw new Error();
        }
      });
      if (!flag) return;
      this.tableData3.forEach(item => {
        if (item.goodsPackageDiscountPrice > item.goodsPackageTotalPrice) {
          flag = false;
          this.$message.error(
            `${item.cityName}${item.businessAreaName}配置的优惠价格大于套餐总额`
          );
          throw new Error();
        }
      });
      return flag;
    }
  },
  watch: {
    goodsPkgDiscountPriceDTO(newvalue) {
      if (newvalue) {
        const {
          baseDiscountPrice,
          cityDiscountPrices,
          businessAreaDiscountPrices
        } = newvalue;
        this.tableData1 = [
          {
            conturay: "全国统一",
            goodsPackageTotalPrice: baseDiscountPrice.goodsPackageTotalPrice,
            goodsPackageDiscountPrice:
              baseDiscountPrice.goodsPackageDiscountPrice
          }
        ];
        this.tableData2 = cityDiscountPrices;
        this.tableData3 = businessAreaDiscountPrices;
        this.merage();
      }
    },
    async goodsPackageDetails(newvalue) {
      if (newvalue) {
        const newarr = await Promise.all(
          newvalue.map(async item => {
            let newObj = {
              areaCode: item.areaCode,
              classifyCode: item.subClassifyCode,
              goodsCode: item.goodsCode,
              skuId: item.skuId
            };
            const { data } = await this.$http({
              url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsSelectedList",
              method: "get",
              params: {
                areaCode: item.areaCode,
                classifyCode: item.subClassifyCode
              }
            });
            newObj.goodsCodeList = data;
            const craftSelectedVos = data.find(
              item1 => item1.goodsCode === item.goodsCode
            ).craftSelectedVos;
            newObj.craftSelectedVos = craftSelectedVos;
            return newObj;
          })
        );
        //console.log(newarr)
        this.ruleForm.goodsPackageDetails = newarr;
      }
    }
  }
};
</script>
<style scoped>
.basic {
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
.Useful {
  font-size: 18px;
  margin-bottom: 15px;
}
.talbe {
  display: flex;
  justify-content: space-between;
}
.buttons {
  position: absolute;
  left: 50%;
  bottom: -70px;
  transform: translateX(-50%);
}
.checkDete {
  display: flex;
}
.checkDete .el-select {
  width: 120px;
  margin-right: 10px;
}
</style>
<style lang="scss" scoped>
/deep/ .el-form-item__label {
  color: #000;
}
</style>
